﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data.OleDb;
using System.Collections;
using DataAccess;
using Entity;
using DataBusiness;
using UI.BasicData;

namespace UI
{
    public partial class frmWellStruct : DevExpress.XtraEditors.XtraForm
    {
        private string ID;

        public frmWellStruct(string ID)
        {
            InitializeComponent();
            BindData();
            this.ID = ID;
        }
        
        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindData()
        {
            this.gridConWellStruct.DataSource = WellStructBLL.GetWellStruct().Tables[0];
            gridView1.Columns[10].Visible = false;
            gridView1.Columns[11].Visible = false;
            gridView1.OptionsView.ColumnAutoWidth = true;
            gridView1.BestFitColumns();//数据自动适应行宽
            //gridView1.PopulateColumns();
        }

        /// <summary>
        /// 导出数据到excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simBtnOutput_Click(object sender, EventArgs e)
        {
            //打开保存对话框
            SaveFileDialog fileDialog = new SaveFileDialog();
            //选择文件类型
            fileDialog.Title = "导出数据表到Excel表格";
            fileDialog.Filter = "Excel文件(*.xls)|*.xls";
            DialogResult dialogResult = fileDialog.ShowDialog(this);
            if (dialogResult == DialogResult.OK)
            {
                //设置文件名
                DevExpress.XtraPrinting.XlsExportOptions options =
                    new DevExpress.XtraPrinting.XlsExportOptions();
                //设置保存文件名
                gridConWellStruct.ExportToXls(fileDialog.FileName);
                //提示导出成功
                DevExpress.XtraEditors.XtraMessageBox.Show("导出成功", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                //设置取消警告
                DevExpress.XtraEditors.XtraMessageBox.Show("您已经取消导出！",
                    "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simBtnInput_Click(object sender, EventArgs e)
        {
            ////标志变量标识是否发起数据导入行为
            //int isInputFlag = 1;
            ////查看当前数据库数据表中是否有记录
            //if (this.gridView1.RowCount >= 1)
            //{
            //    //询问用户是否愿意使用新导入的记录覆盖原来的记录
            //    DialogResult isAgreeRewrite = DevExpress.XtraEditors.XtraMessageBox.Show("数据表已有数据，是否覆盖原有数据？","警告",
            //        MessageBoxButtons.OKCancel,MessageBoxIcon.Warning);
            //    if(isAgreeRewrite == DialogResult.Cancel)
            //    {
            //        isInputFlag = 0;
            //    }
            //}
            
            ////发起数据导入行为
            //if(isInputFlag == 1)
            //{
            //    //打开对话框
            //    OpenFileDialog fileDialog = new OpenFileDialog();
            //    //选择文件类型
            //    fileDialog.Title = "从Excel表格导入数据";
            //    fileDialog.Filter = "Excel2003文件(*.xls)|Excel2007文件(*.xls)|Excel文件(*.xls)|*.xls";
            //    //设置初始化文件打开路径(设置为"我的文档")
            //    fileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            //    //获取得到的文件名
            //    string nameStr = string.Empty;

            //    fileDialog.ValidateNames = true;
            //    fileDialog.CheckPathExists = true;
            //    fileDialog.CheckFileExists = true;

            //    DialogResult dialogResult = fileDialog.ShowDialog();
            //    if (dialogResult == DialogResult.OK)
            //    {
            //        //设置获取的文件名(文件路径)
            //        nameStr = fileDialog.FileName;
            //    }
            //    if (nameStr.Equals(""))
            //    {
            //        DevExpress.XtraEditors.XtraMessageBox.Show("您没有选择任何Excel文件!", "警告",
            //            MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //        return;
            //    }
            //    //从excel文件中获取数据
            //    DataTable dt = excelToDataTable(nameStr);
            //    //dt.Columns[0].ColumnName = "套管程序";
            //    //dt.Columns[1].ColumnName = "井眼尺寸(mm)";
            //    //dt.Columns[2].ColumnName = "完钻深度(m)";
            //    //dt.Columns[3].ColumnName = "尺寸(mm)";
            //    //dt.Columns[4].ColumnName = "下入井段(m)";
            //    //dt.Columns[5].ColumnName = "套管鞋层位";
            //    //dt.Columns[6].ColumnName = "水泥反深(m)";
            //    DataTable tempDT = new DataTable();
            //    tempDT.Columns.Add(new DataColumn("套管程序", typeof(string)));
            //    tempDT.Columns.Add(new DataColumn("井眼尺寸(mm)", typeof(string)));
            //    tempDT.Columns.Add(new DataColumn("完钻深度(m)", typeof(string)));
            //    tempDT.Columns.Add(new DataColumn("尺寸(mm)", typeof(string)));
            //    tempDT.Columns.Add(new DataColumn("下入井段开始(m)", typeof(string)));
            //    tempDT.Columns.Add(new DataColumn("下入井段结束(m)", typeof(string)));
            //    tempDT.Columns.Add(new DataColumn("套管鞋层位", typeof(string)));
            //    tempDT.Columns.Add(new DataColumn("水泥反深(m)", typeof(string)));
                
            //    DataRow dr;

            //    string[] wellsection;
            //    foreach (DataRow row in dt.Rows)
            //    {
            //        dr = tempDT.NewRow();
            //        dr["套管程序"] = row["套管程序"];
            //        dr["井眼尺寸(mm)"] = row["井眼尺寸(mm)"];
            //        dr["完钻深度(m)"] = row["完钻深度(m)"];
            //        dr["尺寸(mm)"] = row["尺寸(mm)"];
            //        dr["套管鞋层位"] = row["套管鞋层位"];
            //        dr["水泥反深(m)"] = row["水泥反深(m)"];

            //        wellsection = row["下入井段(m)"].ToString().Split('~');
            //        dr["下入井段开始(m)"] = wellsection[0];
            //        dr["下入井段结束(m)"] = wellsection[1];
            //        tempDT.Rows.Add(dr);
            //    }

            //    //更新数据库数据表(覆盖原有数据)
            //    WellStructEntity[] wellstructs;
            //    WellStructEntity wellstruct;
            //    ArrayList entityList = new ArrayList();
            //    foreach (DataRow row in tempDT.Rows)
            //    {
            //        wellstruct = new WellStructEntity(well_ID, (string)row["套管程序"], float.Parse(row["井眼尺寸(mm)"].ToString()), float.Parse(row["完钻深度(m)"].ToString()),
            //            float.Parse(row["尺寸(mm)"].ToString()), float.Parse(row["下入井段开始(m)"].ToString()), float.Parse(row["下入井段结束(m)"].ToString()), (string)row["套管鞋层位"], float.Parse(row["水泥反深(m)"].ToString()));
            //        entityList.Add(wellstruct);
            //    }
            //    wellstructs = (WellStructEntity[])entityList.ToArray(typeof(WellStructEntity));
            //    if(AccessHelper.inputTransactionOp("well_struct_number >= 0", "well_struct", wellstructs))
            //    {
            //        DevExpress.XtraEditors.XtraMessageBox.Show("导入数据成功", "提示",
            //            MessageBoxButtons.OK, MessageBoxIcon.Information);
            //        //更新展示数据表
            //        dispDt.Clear();
            //        foreach (DataRow row in dt.Rows)
            //        {
            //            dr = dispDt.NewRow();
            //            dr["套管程序"] = row["套管程序"];
            //            dr["井眼尺寸(mm)"] = row["井眼尺寸(mm)"];
            //            dr["完钻深度(m)"] = row["完钻深度(m)"];
            //            dr["尺寸(mm)"] = row["尺寸(mm)"];
            //            dr["下入井段(m)"] = row["下入井段(m)"];
            //            dr["套管鞋层位"] = row["套管鞋层位"];
            //            dr["水泥反深(m)"] = row["水泥反深(m)"];
            //            dispDt.Rows.Add(dr);
            //        }
            //        sourceDT = tempDT;
            //    }
            //    else
            //    {
            //        DevExpress.XtraEditors.XtraMessageBox.Show("导入数据失败！", "提示",
            //            MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    }
            //}
            
        }

        /// <summary>
        /// 通过path连接excel文件，并从中取出数据填充到datatable中
        /// </summary>
        /// <param name="filePath"></param>
        private DataTable excelToDataTable(string filePath)
        {
            //excel连接字符串
            string excelConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+filePath+";"
                +"Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";
            OleDbConnection oledbconn = new OleDbConnection(excelConnStr);
            oledbconn.Open();

            //获取表名
            DataTable schemaTB = oledbconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null);
            string tableName = schemaTB.Rows[0][2].ToString().Trim();

            //查询表中的所有数据
            string execSql = "select * from [" + tableName + "]";
            OleDbDataAdapter oda = new OleDbDataAdapter(execSql,oledbconn);
            DataSet ds = new DataSet();
            oda.Fill(ds,"well_struct_sheet");

            return ds.Tables[0];

        }

        /// <summary>
        /// 删除井身结构
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要删除选中的记录吗？", "删除提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning,
                MessageBoxDefaultButton.Button2, 0, false) == DialogResult.Yes)
            {
                int selectrowcount = gridView1.SelectedRowsCount;
                if (selectrowcount > 0)
                {
                    string colValue0 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[0]).ToString();
                    if(WellStructBLL.DeleteWellStruct(colValue0) > 0)
                    {
                        gridView1.DeleteSelectedRows();
                        DevExpress.XtraEditors.XtraMessageBox.Show("删除成功", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("删除失败", "提示",
                         MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    
                }
            }
        }

        /// <summary>
        /// 添加井身结构
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simBtnAddItem_Click(object sender, EventArgs e)
        {
            frmWellStructAdd wellStructAdd = new frmWellStructAdd(ID);
            wellStructAdd.StartPosition = FormStartPosition.CenterScreen;
            wellStructAdd.ShowDialog();
            if (wellStructAdd.returnFlag == 1)
            {
                BindData();
            }
        }

        /// <summary>
        /// 修改井身结构
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void editItem_Click(object sender, EventArgs e)
        {
            string colValue0 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[0]).ToString();
            string colValue1 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[1]).ToString();
            string colValue2 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[2]).ToString();
            string colValue3 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[3]).ToString();
            string colValue4 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[4]).ToString();
            string colValue5 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[5]).ToString();
            string colValue6 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[6]).ToString();
            string colValue7 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[7]).ToString();
            string colValue8 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[8]).ToString();
            string colValue9 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[9]).ToString();
            string colValue10 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[10]).ToString();
            string colValue11 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[11]).ToString();
            string colValue12 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[12]).ToString();
            string colValue13 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[13]).ToString();
            string colValue14 = this.gridView1.GetRowCellValue(this.gridView1.FocusedRowHandle, this.gridView1.Columns[14]).ToString();
            tb_WellStructModel wellStructModel = new tb_WellStructModel();
            wellStructModel.ID = string.IsNullOrEmpty(colValue0) ? 0 : Convert.ToInt32(colValue0);
            wellStructModel.WellNo = string.IsNullOrEmpty(colValue1) ? String.Empty : Convert.ToString(colValue1);
            wellStructModel.CasingProgram = string.IsNullOrEmpty(colValue2) ? String.Empty : Convert.ToString(colValue2);
            wellStructModel.HoleSize = string.IsNullOrEmpty(colValue3) ? 0 : Convert.ToDecimal(colValue3);
            wellStructModel.TotalDepth = string.IsNullOrEmpty(colValue4) ? 0 : Convert.ToDecimal(colValue4);
            wellStructModel.WellSize = string.IsNullOrEmpty(colValue5) ? 0 : Convert.ToDecimal(colValue5);
            wellStructModel.StartLocation = string.IsNullOrEmpty(colValue6) ? 0 : Convert.ToDecimal(colValue6);
            wellStructModel.EndLocation = string.IsNullOrEmpty(colValue7) ? 0 : Convert.ToDecimal(colValue7);
            wellStructModel.CasingShoe = string.IsNullOrEmpty(colValue8) ? String.Empty : Convert.ToString(colValue8);
            wellStructModel.CementDepth = string.IsNullOrEmpty(colValue9) ? 0 : Convert.ToDecimal(colValue9);
            wellStructModel.UserID = string.IsNullOrEmpty(colValue10) ? Guid.NewGuid() : Guid.ParseExact(colValue10, "D");
            wellStructModel.InputDate = string.IsNullOrEmpty(colValue11) ? DateTime.Now : Convert.ToDateTime(colValue11);
            wellStructModel.Fpdfd = string.IsNullOrEmpty(colValue12) ? 0 : Convert.ToDecimal(colValue12);
            wellStructModel.Wdotnd = string.IsNullOrEmpty(colValue13) ? 0 : Convert.ToDecimal(colValue13);
            wellStructModel.Mdfdfnd = string.IsNullOrEmpty(colValue14) ? 0 : Convert.ToDecimal(colValue14);
            frmWellStructEdit wellStructEdit = new frmWellStructEdit(wellStructModel);
            wellStructEdit.StartPosition = FormStartPosition.CenterScreen;
            wellStructEdit.ShowDialog();
            if (wellStructEdit.returnFlag == 1)
            {
                BindData();
            }
        }

        /// <summary>
        /// 选择套管程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simBtnSelect_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.comBoxCasParam.Text.ToString()))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请选择套管程序", "提示",
                         MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if(this.comBoxCasParam.Text.ToString()=="全部")
                {
                    BindData();
                }else
                {
                    this.gridConWellStruct.DataSource = WellStructBLL.GetWellStructByCasingProgram(this.comBoxCasParam.Text.ToString()).Tables[0];
                    gridView1.Columns[10].Visible = false;
                    gridView1.Columns[11].Visible = false;
                    gridView1.OptionsView.ColumnAutoWidth = true;
                    gridView1.BestFitColumns();//数据自动适应行宽
                }
            }
        }
    }
}